package org.groovyflow.spring.web;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Holds objects in a session that will be removed from the session
 * the first time they are not accessed during the course of a request.
 * (I think Grails has someting like this.
 * @author ctassoni
 *
 */
public class Chain implements java.io.Serializable{
	private static final long serialVersionUID = -7924807794629651600L;
	
	public static final String KEY = "chain";
	private Set doNotDeleteIfKeyCanBeFoundHere = new HashSet();
	private Map map = new HashMap();
	
	
	public Object get(Object key){
		doNotDeleteIfKeyCanBeFoundHere.add(key);
		return map.get(key);
	}
	
	public void set(Object key, Object value){
		doNotDeleteIfKeyCanBeFoundHere.add(key);
		map.put(key, value);
	}
	
	void clean(){
		for(Iterator iter = map.keySet().iterator(); iter.hasNext(); ){
			Object key = iter.next();
			if(! doNotDeleteIfKeyCanBeFoundHere.contains(key))
				map.remove(key);
		}
		doNotDeleteIfKeyCanBeFoundHere.clear();
	}
	
	
	static void reset(HttpServletRequest req){
		HttpSession sess = req.getSession();
		Chain chain = (Chain) sess.getAttribute(KEY);
		if(chain == null){
			chain = new Chain();
			sess.setAttribute(KEY,chain);
		}
		chain.clean();
	}
	

}
